<template>
  <div class="container-box">
    <div id="chartArea" ref="chartArea" style="width:100%;height:100%;"></div>
  </div>
</template>
<script lang="ts">
import * as echarts from 'echarts';
import { defineComponent, ref, nextTick, watch, getCurrentInstance } from 'vue';
export default defineComponent({
  name: 'LineEchart',
  props: {
    nodes: {
      type: Object,
      default: () => { return [] } 
    }
  },
  setup(props) {
    const instance: any = getCurrentInstance();
    const GL = instance.appContext.config.globalProperties;
    let myChart:any
    const chartArea = ref()
    const data: any = ref([])
    let flag = true
    watch(
        () => props.nodes,
        (old, val) => {
          if( val && old !== val) {
            data.value = old;
            initData()
            initChart()
          }
        },
        { immediate: true, deep: true }
    );
    const option: any = ref({
      tooltip: {
        trigger: 'axis',
        formatter:function(v){
          return v[0] ? v[0].seriesName+'：' +GL.$utils.formatFileSize(v[0].value * 1000 * 1000 ) : ''
        },
      },
      grid: {
        left: "80px",
        right: "40px",
        bottom: "30px",
        top: "50px",
      },
      title:{
        text: '时实流量：',
        textStyle: {
          fontSize: 14
        }
      },
      xAxis: [
        {
          show: false,
          type: 'category',
          boundaryGap: false,
        }
      ],
      yAxis: [
        {
          type: 'value'
        }
      ],
      series: []
    })
    const initChart = () => {
      nextTick(() => {
        myChart = echarts.init(chartArea.value)
        myChart && myChart.setOption(option.value)
      })
    }
    const initData = () => {
      let _ydata: any = [];
      const nodes = data.value
      if(!flag) {
        nodes && nodes.forEach((item: any,index: number) => {
          const Flow = GL.$utils.formatFileSizes(Number(item.Flow)) || 0
          _ydata.push(Flow)
          option.value.series[index].data.push(..._ydata)
          if(option.value.series[index].data.length > 10) {
            option.value.series[index].data.shift()
          }
        })
      } else {
        flag = false
        nodes && nodes.forEach((item: any,index: number) => {
          const Flow = GL.$utils.formatFileSizes(Number(item.Flow)) || 0
          _ydata.push(Flow)
          option.value.series=[{
            name:  item.StreamID,
            data: [..._ydata],
            type: 'line',
            areaStyle: {}
          }]
        })
      }
    }
    return {
      chartArea
    }
  }
})

</script>
<style lang="scss" scoped>
.container-box{
  height: 300px;
  width: 400px;
}
</style>